'use strict';
// 云函数 获取成绩列表
exports.main = async (event, context) => {
  const {
	  collectionName,
    page = 1,       // 页码
    pageSize = 10,  // 每页数量
    filter = {},    // 筛选条件
    orderBy = 'createAt', // 排序字段
    orderType = 'desc'      // 排序方式
  } = event
  
  const db = uniCloud.database()
  const collection = db.collection(collectionName)
  
  const skip = (page - 1) * pageSize
  
  try {
    // 并行查询数据和总数
    const [dataRes, countRes] = await Promise.all([
      collection
        .where(filter)
        .skip(skip)
        .limit(pageSize)
        // .orderBy(orderBy, orderType)
        .get(),
      collection.where(filter).count()
    ])
    // console.log(countRes)
    const total = countRes.total
    const totalPages = Math.ceil(total / pageSize)
    console.log(dataRes)
    return {
      code: 0,
      message: 'success',
      data: {
        list: dataRes.data,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages,
          hasNext: page < totalPages,
          hasPrev: page > 1
        }
      }
    }
  } catch (e) {
    return {
      code: -1,
      msg: e.message,
      data: null
    }
  }
}